//
//  WDResetController.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/11/29.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "WDResetController.h"
#import "WDLoginController.h"
#import "WDForgetMessage.h"
#import "WDPersonDetailController.h"
#import "WDPromptBox.h"
#import "UIViewController+WDShowAlertController.h"

@interface WDResetController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *resetPwdText;
@property (weak, nonatomic) IBOutlet UITextField *surePwdText;
@property (weak, nonatomic) IBOutlet UIButton *resetBtn;
/** 请求信息 */
@property (nonatomic, strong) WDForgetMessage *message;

@end

@implementation WDResetController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //加载导航条
    [self loadNavItemWithAction:@selector(clickBackBtn) btnImage:@"icon_back" btnSelImage:@"icon_back" title:@"重置密码"];
    
    //加载重置按钮
    [self setUpResetBtn];
    
    //监听文本框输入的实时变化
    [self.resetPwdText addTarget:self action:@selector(valueChanged)  forControlEvents:UIControlEventEditingChanged];
    
    [self.surePwdText addTarget:self action:@selector(valueChanged)  forControlEvents:UIControlEventEditingChanged];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self preferredStatusBarStyle];
}

//设置StatusBar样式
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)valueChanged
{
    if (self.resetPwdText.text.length >= 6 && self.surePwdText.text.length >= 6)
    {
        self.resetBtn.enabled = YES;
        self.resetBtn.backgroundColor = WDNavSeleColor;
        
        //WDLog(@"%zd,%zd", self.resetPwdText.text.length, self.surePwdText.text.length);
    } else {
        self.resetBtn.enabled = NO;
        self.resetBtn.backgroundColor = WDUnSeleColor;
        
        //WDLog(@"%zd,%zd", self.resetPwdText.text.length, self.surePwdText.text.length);
    }
}

#pragma mark - 点击事件
- (void)clickBackBtn
{
    [self creatAlert];
}

- (IBAction)clickResetBtn {
    
    [self.view endEditing:YES];
    
    //判断密码是否是6-16位数字或字母
    
    //判断两次密码是否一致
    if(![self.resetPwdText.text isEqualToString:self.surePwdText.text])
    {
        [self showAlertWithMessage:@"两次输入的密码不一致"];
        
    } else {
        
        [self sendPostRequest];
    }
}

#pragma mark - 发送网络请求
- (void)sendPostRequest
{
    NSString *newPwd = [MD5Util md5:self.resetPwdText.text];
    NSDictionary *parameters = @{
                                 @"uid":self.uid,
                                 @"new_pwd":newPwd,
                                 @"sub_pwd":newPwd,
                                 @"ctype":@3
                                 };
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLResetPwd];
    
    [manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //WDLog(@"%@", responseObject);
        
        self.message = [WDForgetMessage mj_objectWithKeyValues:responseObject];
        
        if (self.message.error_code == 0) {
            //修改成功
            
            [WDPromptBox showPromptBoxWithMassage:@"修改成功"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                //跳转主页
                [self.navigationController popToRootViewControllerAnimated:YES];
                
            });
            
        } else {
            [self showAlertWithMessage:self.message.error_msg];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //WDLog(@"%@",error);
        
    }];
}

/** 返回弹出提示框 */
- (void)creatAlert
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:@"你是否要放弃重置密码" preferredStyle:UIAlertControllerStyleAlert];
    
    //确定
    UIAlertAction *certain  = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        //返回上一页
        for (UIViewController *tempV in self.navigationController.viewControllers) {
            
            if ([self.navigationController.viewControllers isKindOfClass:[WDPersonDetailController class]]) {
                
                //跳转个人详情页
                WDPersonDetailController *temp = (WDPersonDetailController *)tempV;
                [self.navigationController popToViewController:temp animated:YES];
                
            } else {
                //跳转登录页
                WDLoginController *temp = (WDLoginController *)tempV;
                [self.navigationController popToViewController:temp animated:YES];
            }
            
        }
        
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    //取消
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //WDLog(@"用户继续要继续重置密码");
    }];
    
    [alert addAction:certain];
    [alert addAction:cancel];
    
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)setUpResetBtn
{
    self.resetBtn.backgroundColor = WDUnSeleColor;
    self.resetBtn.layer.cornerRadius = 2;
    self.resetBtn.clipsToBounds = YES;
}

#pragma mark - <UITextFieldDelegate>
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.resetPwdText) {
        
        [self.resetPwdText resignFirstResponder];
        
        [self.surePwdText becomeFirstResponder];
        
    } else if (textField == self.surePwdText) {
        
        [textField resignFirstResponder];
        
    }
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    if (string.length == 0) return YES;
    
    NSInteger existedLength = textField.text.length;
    
    NSInteger selectedLength = range.length;
    
    NSInteger replaceLength = string.length;
    
    if (existedLength - selectedLength + replaceLength > 16) {
        
        return NO;
    }
    
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

@end
